package 最大二叉树;

import java.util.Arrays;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 最大二叉树
 * @date 2022/11/6 13:57
 */
public class Demo654 {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if(nums.length==0){
            return null;
        }
        if(nums.length==1){
            return new TreeNode(nums[0]);
        }
        int max=Integer.MIN_VALUE;
        int index=-1;
        //找到最大值的位置
        for (int i = 0; i < nums.length; i++) {
            if(nums[i]>max){
                max=nums[i];
                index=i;
            }
        }
        TreeNode root=new TreeNode(nums[index]);
        int[] left=Arrays.copyOfRange(nums,0,index);
        int[] right=Arrays.copyOfRange(nums,index+1,nums.length);
        root.left=constructMaximumBinaryTree(left);
        root.right=constructMaximumBinaryTree(right);
        return root;

    }


     public class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode() {}
         TreeNode(int val) { this.val = val; }
         TreeNode(int val, TreeNode left, TreeNode right) {
             this.val = val;
             this.left = left;
             this.right = right;
         }
     }

}
